package cn.edu.tju.cas.rest.controller;

import cn.edu.tju.cas.entity.UserEntity;
import cn.edu.tju.cas.entity.UserGroupApplyEntity;
import cn.edu.tju.cas.rest.aspect.RequiredAdmin;
import cn.edu.tju.cas.util.*;
import cn.edu.tju.cas.service.ApplyService;
import cn.edu.tju.cas.service.GroupService;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by catold on 16/3/13.
 */
@Controller
@RequestMapping("apply")
public class ApplyController {
    @Autowired
    private GroupService groupService;
    @Autowired
    private ApplyService applyService;

    private static Logger logger = LoggerFactory.getLogger(ApplyController.class);

    // TODO 跟管理员相关的
    @RequiredAdmin
    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody
    Object getByState(@RequestParam(value = "state", required = false) Integer state) {
        StateCode stateCode = StateCode.buildCode(BizCode.SUCCESS);
        if(state == null){
            stateCode.addData("applies", applyService.findAll());
        } else {
            stateCode.addData("applies", applyService.queryByStateAndRelation(state));
        }

        return stateCode;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public @ResponseBody
    Object getById(@PathVariable("id") Integer id) {
        StateCode stateCode = StateCode.buildCode(BizCode.SUCCESS);
        stateCode.addData("apply", applyService.findById(id));

        return stateCode;
    }


    @RequiredAdmin
    @RequestMapping(value = "/{apply_id}/state/{state_code}", method = RequestMethod.PUT)
    public @ResponseBody
    StateCode updateApplyState(@PathVariable("apply_id") Integer apply_id, @PathVariable("state_code") Integer state_code) {
        StateCode stateCode = StateCode.buildCode(BizCode.SUCCESS);

        UserGroupApplyEntity userGroupApplyEntity = applyService.findById(apply_id);
        userGroupApplyEntity.setStatus(state_code);
        // 设置审核人
        userGroupApplyEntity.setCheckerName(SessionUtil.getUser().getUsername());
        applyService.update(userGroupApplyEntity);
        stateCode.addData("result", Constants.UPDATE_RESULT_SUCCESS);
        return stateCode;
    }

    /**
     * 暂时以 Json 格式对象提交
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody
    StateCode apply(@RequestBody NewApply newApply,HttpServletRequest request) {
        // 暂时做一步 登录检查，全局配置后，去掉
        UserEntity userEntity = SessionUtil.getUser();

        StateCode stateCode = StateCode.buildCode(BizCode.SUCCESS);
        UserGroupApplyEntity userGroupApplyEntity = applyService.saveNewApply(userEntity, newApply);


         // to do
        stateCode.addData("apply",userGroupApplyEntity);
        return stateCode;
    }

    /**
     * 文件上传接口
     * @param request
     * @return
     */
    @RequestMapping(value = "/file", method = RequestMethod.POST)
    public @ResponseBody StateCode uploadMultiFile(MultipartHttpServletRequest request) throws IOException {

        StateCode stateCode = StateCode.buildCode(BizCode.SUCCESS);

        Map<String,MultipartFile> fileMap = request.getFileMap();
        System.out.println("上传的文件个数为：" + fileMap.size());
        Set<String> fileSet = fileMap.keySet();
        Iterator<String> fileNameIterator = fileSet.iterator();

        ArrayList<String> urls = new ArrayList<>();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
        String getDateString = sdf.format(new Date());

        String uniqueDir = String.valueOf(System.nanoTime());
        // 上传文件保存位置
        String targetDir = request.getSession().getServletContext().getRealPath("/WEB-INF") + File.separatorChar + "upload" + File.separatorChar + getDateString + File.separatorChar + uniqueDir;

        System.out.println("当前文件为位置：" + this.getClass().getResource("/"));

        URL base = this.getClass().getResource("/"); //先获得本类的所在位置，如/home/popeye/testjava/build/classes/net/
        String path = new File(base.getFile(), "..\\"+"upload").getCanonicalPath(); //就可以得到/home/popeye/testjava/name

        System.out.println("得到的位置：" + path);

        if(Constants.SYSTEM_TYPE.contains("windows")){  // 是 windows
            targetDir  = "D:\\upload\\file\\" + getDateString +"\\"+ uniqueDir+"\\";
        }else{   // 是 linux
            targetDir = "/opt/upload/file/" + getDateString +"/"+ uniqueDir;
        }
        System.out.println("文件位置：" + request.getSession().getServletContext().getRealPath("upload/img/product"));
        System.out.println("文件保存位置文件夹：" + targetDir);
        String baseUrl =  Constants.BASE_HTTP+"/upload/file/" + getDateString + "/" + uniqueDir;;

        while(fileNameIterator.hasNext()){
            String uploadFileName = fileNameIterator.next();
            System.out.println(uploadFileName);
            MultipartFile file = fileMap.get(uploadFileName);

            if (file == null || file.getSize() <= 0) {// step-2 判断file
                System.out.println("size 为 0");
                continue;
            }
            urls.add(applyService.uploadFile(file, targetDir, baseUrl));
        }
        stateCode.addData("urls",urls);
        return stateCode;
    }



}
